package com.yk.banner.widget;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.yk.banner.R;
import com.yk.banner.callback.Indicator;

public class TextIndicatorView extends androidx.appcompat.widget.AppCompatTextView implements Indicator {

    /**
     * 控制在banner中的位置
     */
    private RelativeLayout.LayoutParams params;
    private int pagerCount;

    public TextIndicatorView(@NonNull Context context) {
        super(context);
        init();
    }

    public TextIndicatorView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TextIndicatorView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable.text_indicator_bg);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            setBackground(drawable);
        } else {
            setBackgroundDrawable(drawable);
        }
        setGravity(Gravity.CENTER);
        setTextColor(Color.WHITE);
        setPadding(dip2px(8), dip2px(1), dip2px(8), dip2px(1));
    }

    @Override
    public void initIndicatorCount(int pagerCount, int currentPage) {
        this.pagerCount = pagerCount;
        setVisibility(pagerCount > 1 ? VISIBLE : GONE);
        setText("1/" + pagerCount);
        requestLayout();
    }

    @Override
    public View getView() {
        return this;
    }

    @Override
    public RelativeLayout.LayoutParams getParams() {
        if (params == null) {
            params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            //params.addRule(RelativeLayout.CENTER_HORIZONTAL);
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            params.bottomMargin = dip2px(16);
            params.rightMargin = dip2px(20);
        }
        return params;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setText((position + 1) + "/" + pagerCount);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private int dip2px(float dp) {
        return (int) (dp * getContext().getResources().getDisplayMetrics().density);
    }

}
